package day07.concurrent04;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWriteLock - 读锁和写锁无法共存
 */
public class Demo02 {
    public static void main(String[] args) {
        ReadWriteLock lock = new ReentrantReadWriteLock();
        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.writeLock().lock();
                System.out.println("线程2加写锁");
                System.out.println("线程2写入数据...");
                try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
                lock.writeLock().unlock();
                System.out.println("线程2释放写锁");
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.readLock().lock();
                System.out.println("线程1加读锁");
                System.out.println("线程1读取数据...");
                try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
                lock.readLock().unlock();
                System.out.println("线程1释放读锁");
            }
        }).start();


    }
}
